<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-left">
      <div class="jsbos-common-title">
        <h2>省市区域</h2>
        <span class="options">
          <el-tooltip effect="light" content="折叠" placement="top">
            <el-link icon="el-icon-arrow-up" @click="foldTree()" />
          </el-tooltip>
          <el-tooltip effect="light" content="刷新" placement="top">
            <el-link
              icon="icon-ym icon-ym-Refresh jsbos-common-head-icon"
              @click="addressReset()"
            />
          </el-tooltip>
        </span>
      </div>
      <el-scrollbar
        class="jsbos-common-el-tree-scrollbar"
        v-loading="treeLoading"
      >
        <el-tree
          ref="treeBox"
          :data="treeData"
          :props="defaultProps"
          check-on-click-node
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @node-click="handleNodeClick"
          class="jsbos-common-el-tree"
          v-if="refreshTree"
          lazy
          :load="loadNode"
        >
          <span
            class="custom-tree-node"
            slot-scope="{ data, node }"
            :title="data.fullName"
            @mouseenter="mouseEnter(data, true)"
            @mouseleave="mouseEnter(data, false)"
          >
            <span class="text" :title="data.fullName">{{ node.label }}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="jsbos-common-layout-center jsbos-flex-main">
      <el-row class="jsbos-common-search-box" :gutter="18">
        <el-form @submit.native.prevent>
          <!-- style="margin-left: 20px; position: absolute; left: 100px" -->
          <el-col
            class="form-BtnNowarp"
            :span="10"
            style="display: inline-block; margin-left: 8px"
          >
            <!-- <div
              class="form-BtnNowarp"
              style="display: inline-block; float: left; margin-left: 8px"
            > -->
            <el-radio-group
              v-model="organizeFlag"
              @change="searchByOrganizeIds"
            >
              <div
                v-for="item in companyList"
                :key="item.id"
                style="display: inline-block"
              >
                <el-radio-button :label="item.id">{{
                  item.fullName
                }}</el-radio-button>
              </div>
            </el-radio-group>
            <!-- </div> -->
          </el-col>

          <el-col :span="4">
            <el-form-item label="姓名">
              <el-input
                v-model="listQuery.keyword"
                placeholder="请输入姓名"
                clearable
                @keyup.enter.native="search()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item class="form-BtnNowarp">
              <el-button type="primary" icon="el-icon-search" @click="search()">
                {{ $t("common.search") }}</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >{{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div style="position: relative; float: left">
            <user-select
              v-model="userId"
              placeholder=""
              :multiple="true"
              style="opacity: 0; position: absolute; width: 80px !important"
              @callbackAddressAuthorize="authorizeAddress"
              :listQueryAddress="listQuery.address"
              :judge="true"
            />
            <el-button
              style="z-index: 999; display: flex; width: 80px"
              type="primary"
              icon="el-icon-plus"
              >新授权
            </el-button>
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="tableData"
          :cell-style="changeBackground"
          align="center"
        >
          <el-table-column prop="code" label="工号" width="100" />
          <el-table-column prop="realName" label="姓名" width="100">
            <template slot-scope="scope">
              <el-link
                @click="addOrUpdateHandle(scope.row.id, true)"
                type="primary"
                :underline="false"
              >
                <div v-if="scope.row.afterAreaManagerFlag == '0'">
                  {{ scope.row.realName
                  }}<span style="color: #ffb34d; font-size: 12px"
                    >&nbsp;(主管)</span
                  >
                </div>
                <div v-if="scope.row.afterAreaManagerFlag == '1'">
                  {{ scope.row.realName }}
                </div>
              </el-link>
            </template>
            <!-- <template slot-scope="scope" v-if="!scope.row.areaManagerFlag">
              {{ scope.row.realName }}
            </template> -->
          </el-table-column>
          <el-table-column prop="account" label="账号" width="100" />
          <el-table-column prop="gender" label="性别" width="90" align="center">
            <template slot-scope="scope">
              <span>{{
                scope.row.gender == 1
                  ? "男"
                  : scope.row.gender == 2
                  ? "女"
                  : "保密"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mobilePhone" label="手机" width="120" />
          <el-table-column prop="organize" label="所属组织" min-width="200">
            <template slot-scope="scope">
              <el-tooltip placement="top" effect="light">
                <div v-html="ToBreak(scope.row.organize)" slot="content"></div>
                <div
                  style="
                    overflow: hidden;
                    display: -webkit-box;
                    text-overflow: ellipsis;
                    -webkit-line-clamp: 1;
                    -webkit-box-orient: vertical;
                    white-space: normal;
                  "
                >
                  {{ scope.row.organize }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- show-overflow-tooltip -->
          <el-table-column prop="addressList" label="授权区域" width="120">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="light" placement="top-start">
                <div
                  v-html="ToBreak(scope.row.addressList)"
                  slot="content"
                ></div>
                <div
                  style="
                    overflow: hidden;
                    display: -webkit-box;
                    text-overflow: ellipsis;
                    -webkit-line-clamp: 1;
                    -webkit-box-orient: vertical;
                    white-space: normal;
                  "
                >
                  {{ scope.row.addressList }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="enabledMark"
            label="状态"
            width="70"
            align="center"
          >
            <template slot-scope="scope">
              <el-tag
                type="success"
                disable-transitions
                v-if="scope.row.enabledMark == 1"
                >正常
              </el-tag>
              <el-tag
                type="warning"
                disable-transitions
                v-else-if="scope.row.enabledMark == 2"
                >锁定
              </el-tag>
              <el-tag type="danger" disable-transitions v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope" v-if="!scope.row.isAdministrator">
              <el-button
                type="text"
                :disabled="scope.row.afterAreaManagerFlag == '0'"
                @click="addSaleManager(scope.row.id)"
                >设为主管
              </el-button>
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <el-button
                type="text"
                @click="addOrUpdateHandle(scope.row.id, true)"
                >详情
              </el-button>
              <el-button
                type="text"
                class="jsbos-table-delBtn"
                @click="handleDel(scope.row.id)"
                >移除
              </el-button>
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <Form v-show="formVisible" ref="Form" @close="removeForm" />
    <Diagram
      v-if="diagramVisible"
      ref="Diagram"
      @close="diagramVisible = false"
    />
  </div>
</template>
<script>
import { getProvinceSelector, GetAreaByIds } from "@/api/system/province";
import { getDepartmentSelector } from "@/api/permission/department";
import request from "@/utils/request";
import { getUserInfo, updateUser } from "@/api/permission/user";
import {
  authorizeAddressGetUserList,
  updateUserState,
  unlockUser,
  delUser,
} from "@/api/permission/user";
import Form from "../user/Form.vue";
import Diagram from "./Diagram";
import { isEmpty } from "@/utils/isEmpty";

export default {
  name: "AfterAreaAuth",
  components: {
    Form,
    Diagram,
  },
  props: {
    value: {
      default: () => [],
    },
    level: {
      type: Number,
      default: 1,
    },
    size: String,
  },
  data() {
    return {
      companyList: [],
      //控制用户框是否显示
      watchFlag: true,
      userId: [],
      keyword: "",
      isExpand: false,
      defaultProps: {
        children: "children",
        label: "fullName",
        isLeaf: "isLeaf",
      },
      nodeId: "-1",
      treeData: [],
      tableData: [],
      treeLoading: false,
      listLoading: true,
      organizeFlag: "",
      listQuery: {
        organizeId: "",
        keyword: "",
        organizeFlag: "",
        currentPage: 1,
        pageSize: 20,
        alreadyAuthorize: "",
        address: [],
      },
      total: 0,
      type: "",
      formVisible: false,
      diagramVisible: false,
      resetFormVisible: false,
      authorizeFormVisible: false,
      expands: true,
      refreshTree: true,
      filterText: "",
    };
  },
  watch: {
    filterText(val) {
      this.$refs.treeBox.filter(val);
    },
  },
  created() {
    this.getCompanyList();
    this.initAddressData();
    this.getOrganizeList(true);
  },
  computed: {
    modelId() {
      return this.$route.meta.modelId || "";
    },
  },
  methods: {
    //设为主管
    async addSaleManager(id) {
      const res = await getUserInfo(id);
      let data = res.data;
      if (isEmpty(data.roleId)) {
        data.roleId = "501682437869490309";
      } else {
        data.roleId = data.roleId + ",501682437869490309";
      }
      updateUser(data).then((res) => {
        this.$message({
          message: res.msg,
          type: "success",
        });
        this.initData();
      });
      console.log(data);
    },
    //获取公司列表
    getCompanyList() {
      let modelId = this.modelId;
      request({
        url: "/api/permission/Organize/getCompanyList/" + modelId,
        method: "get",
      }).then((res) => {
        this.companyList = res.data;
      });
    },
    //进入页面默认公司
    setDefaultOrganize() {
      let organizeId = this.$store.state.user.userInfo.organizeId;
      console.log(this.$store.state.user.userInfo);
      if (!isEmpty(organizeId)) {
        this.organizeFlag = organizeId;
        this.listQuery.organizeFlag = this.organizeFlag;
        this.initData();
      }
    },
    //标签公司切换检索
    searchByOrganizeIds() {
      this.listQuery.organizeFlag = this.organizeFlag;
      this.initData();
    },
    //改变背景
    changeBackground({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        // if (row.areaManagerFlag === "0") {
        //   return "color:red";
        // }
      }
    },
    //地址栏清空并刷新
    addressReset() {
      this.$refs.treeBox.setCurrentKey(null);
      this.listQuery.address = [];
      this.foldTree();
      this.search();
    },
    //tooltip显示换行
    ToBreak(val) {
      if (!isEmpty(val)) {
        if (val.includes(",")) {
          return val.replaceAll(",", "<br />");
        } else if (val.includes(";")) {
          return val.replaceAll(";", "<br />");
        }
        return val;
      }
    },
    //授权确定按钮回调
    authorizeAddress() {
      if (isEmpty(this.listQuery.address)) {
        this.$message.warning("请选择地区");
        return;
      }
      let data = {
        address: this.listQuery.address,
        userId: this.userId,
      };
      request({
        url: "/api/permission/UserRelation/create",
        method: "post",
        data: data,
      }).then((res) => {
        this.$message.success("添加成功！");
        this.search();
        this.userId = [];
      });
    },
    getOrganizeList(isInit) {
      getDepartmentSelector()
        .then((res) => {
          this.treeLoading = false;
          if (isInit) {
            this.setDefaultOrganize();
          }
        })
        .catch(() => {});
    },
    showDiagram() {
      this.diagramVisible = true;
      this.$nextTick(() => {
        this.$refs.Diagram.init();
      });
    },
    search() {
      this.listQuery.currentPage = 1;
      this.listQuery.pageSize = 20;
      this.listQuery.sort = "desc";
      this.initData();
    },
    reset() {
      this.listQuery.keyword = "";
      this.search();
    },

    initData() {
      this.listLoading = true;
      // this.listQuery.alreadyAuthorize = "true";
      this.listQuery.source = "after";
      authorizeAddressGetUserList(this.listQuery)
        .then((res) => {
          let data = [];
          res.data.list.forEach((s) => {
            if (!isEmpty(s.addressList)) {
              s.addressList = s.addressList.join(",");
              data.push(s);
            } else {
              data.push(s);
            }
          });
          this.tableData = data;
          this.total = res.data.pagination.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.Form.init(
          id,
          isDetail,
          this.type === "department" ? this.listQuery.organizeId : ""
        );
      });
    },
    removeForm(isRefresh) {
      this.formVisible = false;
      if (isRefresh) {
        this.keyword = "";
        this.initData();
      }
    },
    removeAuthorizeForm(isRefresh) {
      this.authorizeFormVisible = false;
      if (isRefresh) {
        this.keyword = "";
        this.initData();
      }
    },
    handleUpdateState(row) {
      const txt = row.enabledMark ? "禁用" : "开启";
      this.$confirm(`您确定要${txt}当前用户吗, 是否继续?`, "提示", {
        type: "warning",
      })
        .then(() => {
          updateUserState(row.id).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              duration: 1000,
              onClose: () => {
                row.enabledMark = row.enabledMark ? 0 : 1;
              },
            });
          });
        })
        .catch(() => {});
    },
    handleDel(id) {
      let arr = [];
      arr.push(id);
      let data = {
        address: this.listQuery.address,
        userId: arr,
      };
      if (isEmpty(this.listQuery.address)) {
        this.$confirm("此操作将取消该用户所有授权区域, 是否继续?", "提示", {
          type: "error",
        }).then(() => {
          this.requestDel(data);
        });
      } else {
        this.$confirm("此操作将取消该用户此授权区域, 是否继续?", "提示", {
          type: "warning",
        }).then(() => {
          this.requestDel(data);
        });
      }
    },
    requestDel(data) {
      request({
        url: "/api/permission/UserRelation/delete",
        method: "post",
        data: data,
      }).then((res) => {
        this.$message.success("移除成功！");
        this.search();
      });
    },
    unlockUser(id) {
      this.$confirm("此操作将解除该账户锁定, 是否继续?", "解除锁定", {
        type: "warning",
      })
        .then(() => {
          unlockUser(id).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              duration: 1500,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },

    //获取树状地址数据
    initAddressData() {
      this.Listloading = true;
      getProvinceSelector(this.nodeId).then((res) => {
        this.treeData = res.data.list.map((value) => ({
          ...value,
          isLeaf: 0 >= this.level ? true : value.isLeaf,
        }));
        this.Listloading = false;
      });
    },
    //展开树
    expandTree() {
      this.isExpand = true;
      this.buildData();
    },
    //折叠树
    foldTree() {
      this.isExpand = false;
      this.buildData();
    },
    //遍历树的所有子节点，展开的时候给子节点展开状态赋值true，折叠时候赋值false
    buildData() {
      for (let i = 0; i < this.$refs.treeBox.store._getAllNodes().length; i++) {
        this.$refs.treeBox.store._getAllNodes()[i].expanded = this.isExpand;
      }
    },
    mouseEnter(data, show) {
      data.ifShow = show;
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.nodeId = "-1";
        return resolve(this.treeData);
      }
      this.nodeId = node.data.id;
      getProvinceSelector(this.nodeId).then((res) => {
        const list = res.data.list.map((value) => ({
          ...value,
          isLeaf: node.level >= this.level ? true : value.isLeaf,
        }));
        resolve(list);
      });
    },
    getNodePath(node) {
      let fullPath = [];
      const loop = (node) => {
        if (node.level) fullPath.unshift(node.data);
        if (node.parent) loop(node.parent);
      };
      loop(node);
      return fullPath;
    },
    handleNodeClick(data, node) {
      const nodePath = this.getNodePath(node);
      let currId = nodePath.map((o) => o.id);
      let currData = nodePath.map((o) => o.fullName).join("/");
      this.selectedIds = [currId];
      this.selectedData = [currData];
      this.listQuery.address = this.selectedIds[0];

      this.search();
    },
  },
};
</script>
<style scoped>
.el-select__tags {
  /* display: flex; */
  width: 0;
}
.el-tag {
  display: block;
}

.jsbos-common-head {
  /* display: flex; */
  position: relative;
}
</style>
